package cmd_handler

import (
	"sync"

	"google.golang.org/protobuf/reflect/protoreflect"
)

// 广播员
type broadcaster struct {
	// 内置字典
	innerMap *sync.Map
}

// 单例对象
var broadcasterInstance = &broadcaster{
	innerMap: &sync.Map{},
}

// 获取单例对象
func getBroadcaster() *broadcaster {
	return broadcasterInstance
}

// 添加指令上下文
func (this *broadcaster) addCmdCtx(ctx MyCmdCtx) {
	if nil == ctx ||
		len(ctx.GetSessionUId()) <= 0 {
		return
	}

	this.innerMap.Store(ctx.GetSessionUId(), ctx)
}

// 移除指令上下文
func (this *broadcaster) removeCmdCtxBySessionUId(sessionUId string) {
	if len(sessionUId) <= 0 {
		return
	}

	this.innerMap.Delete(sessionUId)
}

// broadcast 广播消息
func (this *broadcaster) broadcast(pMsgObj protoreflect.ProtoMessage) {
	if nil == pMsgObj {
		return
	}

	this.innerMap.Range(func(k, v interface{}) bool {
		if nil == v {
			return true
		}

		ctx := v.(MyCmdCtx)
		ctx.Write(pMsgObj)

		return true
	})
}
